<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>订单确认</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .navbar {
            background-color: #ff5000;
            color: white;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .navbar .logo {
            display: flex;
            align-items: center;
        }
        .navbar .logo span {
            margin-left: 10px;
        }
        .navbar a {
            color: white;
            text-decoration: none;
            margin: 0 10px;
        }
        .navbar button {
            background-color: white;
            color: #ff5000;
            border: none;
            padding: 5px 10px;
            margin-left: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
        .order-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            display: flex;
            justify-content: space-between;
        }
        .order-details {
            flex: 2;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f5f5f5;
        }
        .order-details h2 {
            font-size: 24px;
            margin-bottom: 10px;
        }
        .order-details p {
            font-size: 16px;
            line-height: 1.6;
            margin: 10px 0;
        }
        .order-details .price {
            color: #ff5000;
            font-size: 20px;
            margin: 10px 0;
        }
        .order-buttons {
            margin-top: 20px;
        }
        .order-buttons button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-right: 10px;
        }
        .confirm-order {
            background-color: #00c800;
            color: white;
        }
    </style>
</head>
<body>
<div class="navbar">
    <div class="logo">机械工业</div>
    <div class="nav-links">
        <a id="index1Link" href="#">首页</a>
        <a id="userMessageLink" href="#">我的</a>
        <a id="cartLink" href="#">购物车</a>
    </div>
</div>

<div class="order-container" id="orderContainer">
    <!-- 订单信息将通过 JavaScript 动态生成 -->
</div>

<script>
    // 获取 URL 中的参数
    function getUserIdFromUrl() {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get('userId');
    }

    const userId = getUserIdFromUrl();
    const userMessageLink = document.getElementById("userMessageLink");
    const index1Link = document.getElementById("index1Link");
    const cartLink = document.getElementById("cartLink");

    userMessageLink.href = `userMessage?id=${userId}`;
    index1Link.href = `index1?id=${userId}`;
    cartLink.href = `cart?id=${userId}`;


    var urlParams = new URLSearchParams(window.location.search);
    var productId = urlParams.get('productId');
    var quantity = urlParams.get('quantity');

    // 获取订单信息并展示
    function loadOrderDetails() {
        // 获取商品信息
        var xhrProduct = new XMLHttpRequest();
        xhrProduct.open('GET', '/products/' + productId, true);
        xhrProduct.onreadystatechange = function () {
            if (xhrProduct.readyState === 4 && xhrProduct.status === 200) {
                var product = JSON.parse(xhrProduct.responseText);

                // 获取用户地址信息
                var xhrAddress = new XMLHttpRequest();
                xhrAddress.open('GET', '/addresses/user/' + userId, true);
                xhrAddress.onreadystatechange = function () {
                    if (xhrAddress.readyState === 4 && xhrAddress.status === 200) {
                        var addresses = JSON.parse(xhrAddress.responseText);

                        var orderContainer = document.getElementById('orderContainer');

                        // 动态生成订单信息的 HTML
                        var html = `
                            <div class="order-details">
                                <h2>订单确认</h2>
                                <p><strong>商品名称：</strong>${product.name}</p>
                                <p><strong>价格：</strong>￥${product.price}</p>
                                <p><strong>数量：</strong>${quantity}</p>
                                <p class="price"><strong>总价：</strong>￥${(product.price * quantity).toFixed(2)}</p>
                                <p><strong>收货地址：</strong>
                                    <select id="addressSelect">
                                        ${addresses.map(addr => `
                                            <option value="${addr.id}">
                                                ${addr.name} - ${addr.province} ${addr.city} ${addr.district} ${addr.addr} ${addr.phone}
                                            </option>
                                        `).join('')}
                                    </select>
                                </p>
                                <div class="order-buttons">
                                    <button class="confirm-order" onclick="confirmOrder(${productId}, ${quantity}, ${userId})">确认订单</button>
                                </div>
                            </div>
                        `;
                        orderContainer.innerHTML = html;
                    }
                };
                xhrAddress.send();
            }
        };
        xhrProduct.send();
    }

    // 确认订单的函数
    function confirmOrder(productId, quantity, userId) {
        var xhrProduct = new XMLHttpRequest();
        xhrProduct.open('GET', '/products/' + productId, true);
        xhrProduct.onreadystatechange = function () {
            if (xhrProduct.readyState === 4 && xhrProduct.status === 200) {
                var product = JSON.parse(xhrProduct.responseText);

                var orderRequest = {
                    userId: userId,
                    addressId: document.getElementById('addressSelect').value, // 获取用户选择的地址ID
                    productId: productId,
                    productName: product.name,
                    productPrice: product.price,
                    quantity: quantity,
                    totalPrice: product.price * quantity
                };
                function generateRandomOrderId() {
                    return Math.floor(Math.random() * 1000000000); // 生成一个随机的订单编号
                }
                var xhrOrder = new XMLHttpRequest();
                xhrOrder.open('POST', '/orders', true);
                xhrOrder.setRequestHeader('Content-Type', 'application/json');
                xhrOrder.onreadystatechange = function () {
                    if (xhrOrder.readyState === 4) {
                        if (xhrOrder.status === 200) {
                            var orderNo=generateRandomOrderId()
                            alert('订单创建成功！');
                            const url = `/payment?orderid=${encodeURIComponent(orderNo)}&price=${encodeURIComponent(orderRequest.totalPrice)}&title=${encodeURIComponent(orderRequest.productName)}`;
                            window.location.href = url;
                        } else {
                            alert('订单创建失败，请重试！');
                        }
                    }
                };
                xhrOrder.send(JSON.stringify(orderRequest));
            }
        };
        xhrProduct.send();
    }

    // 页面加载完成时调用加载订单信息的函数
    window.onload = loadOrderDetails;
</script>
</body>
</html>
